<template>
  <div>
    <el-container>
      <el-header style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon" />
          <span class="primary">导入导出</span>
        </div>
      </el-header>
      <div class="pd10">
        <div style="align-items: center;margin: 10px 0; display: flex;justify-content: space-between;">
          <div>
            <!-- <el-date-picker
              v-model="query.date"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            /> -->
          </div>
          <div>
            <el-button icon="el-icon-download" :loading="downloadChecked" @click="handleDownload">{{ downloadChecked?'&nbsp&nbsp&nbsp正在导出&nbsp&nbsp&nbsp': '导出客户列表' }}</el-button>
            <el-button icon="el-icon-refresh-right" type="primary" @click="daoruClick">导入客户列表</el-button>
          </div>
        </div>
        <el-table ref="table" :data="showExportData" border stripe :height="curHeight">
          <el-table-column label="id" align="center" prop="id" width="60" />
          <el-table-column label="客户名称" align="left" prop="name" width="100" />
          <el-table-column label="等级" align="center" prop="vipName" width="80" />
          <el-table-column label="注册手机" align="center" prop="mobile" width="110" />
          <el-table-column label="金币" align="right" prop="point" width="110" />
          <el-table-column label="消费金额" align="right" prop="amount" width="110" />
          <el-table-column label="推广业绩" align="right" prop="cardBalance" width="110" />
          <el-table-column label="地址" align="left" prop="areaName" min-width="250" />
          <el-table-column label="邮箱" align="left" prop="email" width="150" />
        </el-table>
        <el-pagination
          v-if="total!==0"
          style="padding-top: 15px;"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-footer class="el-footerBox">
        <el-row :gutter="24" style="margin-bottom: 10px">
          <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="primary" :loading="updateChecked" v-show="importData.length>0" @click="updateClick">确认导入</el-button>
        </el-row>
      </el-footer>
      <upload-excel-component ref="upload" :on-success="handleSuccess" :before-upload="beforeUpload" />
    </el-container>
  </div>
</template>

<script>
import { EventBus } from '@/api/eventBus'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { list, batchImport } from '@/api/member'
export default {
  name: 'member-memberExport',
  components: { UploadExcelComponent },
  data() {
    return {
      pageNum: 1,
      pageSize: 20,
      total: 0,
      curHeight: null,
      daoruData: '',
      query: {
        date: [],
      },
      firstSheetName: '',
      importData: [],
      exportData: [],
      showExportData: [],
      updateChecked: false,
      downloadChecked: false,
      pickerOptions: {// 时间快捷选择
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
  },
  methods: {
    comeIn() {
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 330// 减去页面上固定高度height
    },
    updateClick() {
      this.updateChecked = true
      batchImport(this.exportData).then(res => {
        if (res.data.errorNum > 0) {
          this.exportData = res.data.itemList
          this.updateChecked = false
        } else if (res.data.errorNum == 0) {
          this.updateChecked = false
          EventBus.$emit('member-memberExport', res.data)
          this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
            this.$router.push({
              path: '/member/list'
            })
          })// 关闭当前tab回到列表
        }
      }).catch(() => { this.updateChecked = false })
    },
    handleDownload() { // 导出客户列表
      this.downloadChecked = true
      this.prepareExcel().then(() => {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['id', '客户名称', '等级', '注册手机', '金币', '消费金额', '推广业绩', '地址', '邮箱']
          const filterVal = ['id', 'name', 'vipName', 'mobile', 'point', 'amount', 'cardBalance', 'areaName', 'email']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '客户列表',
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        this.downloadChecked = false
      })
    },
    prepareExcel() {
      return new Promise((resolve, reject) => {
        const params = new URLSearchParams()
        if (this.query.date.length > 0) {
          params.append('startDate', this.query.date[0])
          params.append('endDate', this.query.date[1])
        }
        params.append('pageNum', 1)
        params.append('pageSize', 10000)
        params.append('sortField', 'id')
        params.append('direction', 'asc')
        list(params).then(res => {
          this.exportData = res.data.data
          resolve()
        }).catch(() => { this.downloadChecked = false })
      })
    },
    formatJson(filterVal) {
      return this.exportData.map(v => filterVal.map(j => v[j]))
    },
    daoruClick() {
      this.$message({ message: '暂不支持该功能' })
      return
      this.$refs.upload.handleUpload()
    },
    // 导入表单成功回调事件
    handleSuccess({ results, header, firstSheetName }) {
      this.total = results.length
      this.comeIn()
      this.importData = []
      results.forEach(item => {
        if (item.id != '' || item.id != null) {
          var batchData = {
            id: item.id,
            name: item.客户名称,
            vipName: item.等级,
            mobile: item.注册手机,
            point: item.金币,
            amount: item.消费金额,
            cardBalance: item.推广业绩,
            areaName: item.地址,
            email: item.邮箱,
          }
          this.importData.push(batchData)
        }
      })
      this.showExportDataFn(this.pageNum, this.pageSize)
    },
    // //名单导入
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    showExportDataFn(pageNum, pageSize) {
      console.log(this.importData.slice((pageNum - 1) * pageSize, pageNum * pageSize))
      this.showExportData = this.importData.slice((pageNum - 1) * pageSize, pageNum * pageSize)
    },
    handleCurrentChange(value) {
      this.pageNum = value
      this.showExportDataFn(this.pageNum, this.pageSize)
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.showExportDataFn(this.pageNum, this.pageSize)
    }
  }
}
</script>

<style scoped>

</style>
